Code Style Guide


Most of this is totally down to personal preference, but to help everyone else read and understand your code, we need to agree on a few aspects of code formatting.

Documenting a function

Everyone should be aware that there is a page template when creating a new page for a function. Select 'function' as the template from the drop down menu in the middle of the page. I have made this page as an example.

Function and variable names

  • Function names are all lowercase with underscores between words: i_am_a_function(), serial_interrupt().
  • When making function prototypes, include the names of the variables in the prototype (not just their types): convert_unit(int grams, float ratio) is more readable than convert_unit(int, float).
  • Variable names are all lowercase with uppercase letters on the first letter of all words after the first (no spaces): iAmAVariable, currentState.
  • Please try to give variables descriptive names so that it is easier to understand what is going on. For example, use loop1 and loop2 if you have nested loops, instead of i and j.

Error checking

  • The idea of breaking the program into so many parts/modules is that we can re-use each piece many times.
  • Therefore, you need to make any function that you write bulletproof.
  • Don't assume that the input arguments you get when your function is called will be correct. Perform a sanitization pass at the start of your code so that you can correct (or at least catch) any bad values you have been passed.
  • Check for NULL pointers.
  • Make sure that you are working with the right type of primitive (signed vs unsigned, long vs short).
  • Don't make assumptions about the state that the program will be in when your function is called. Check for flags in the PIC registers or the Settings module to make sure that your function will give the right output.
  • When you find an error (even if it has been successfully corrected), use the serial transmission module to give a debug message.
  • If you find an error in someone else's code, inform them or fix it yourself (and then tell them what you changed).
  • Having said all that, try to make sure that your function gives correct and predictable output.

Comments and Peer Review

  • Every function should start with a brief description of what it does and how it does it.
  • Always use plenty of comments - this should be self explanatory.
  • Spend some time going over other people's code (particularly the functions that you call/are called by you), and help them to be more compatible with your code. If they have made a mistake, let them know about it.
Data Types
  • ints are 16b (the C language guarantees at least 16b precision on an int)
  • mass values are processed as ints
  • chars are 8b (as usual)
  • error codes, ascii characters are chars.